from time import sleep
from tkinter import ttk, Entry
from requests import get
from ModeType.Base import BaseOutput

# 接口式输出


class ApiResult(BaseOutput):
    def createConfig(self, root):
        self.commonConfig(root)
        box = ttk.LabelFrame(root, text='api 输出配置')
        box.pack()

        row = 0
        ttk.Label(box, text='接口地址').grid(row=row, column=0)
        self.req_url = Entry(box)
        self.req_url.insert(0, 'http://localhost:7586/api/listData')
        self.req_url.grid(row=row, column=1)

        row += 1
        ttk.Label(box, text='返回结果字段').grid(row=row, column=0)
        self.resKey = Entry(box)
        self.resKey.insert(0, 'data')
        self.resKey.grid(row=row, column=1)

        row += 1
        ttk.Label(box, text='每条数据文案字段').grid(row=row, column=0)
        self.itemKey = Entry(box)
        self.itemKey.insert(0, 'cparagraph')
        self.itemKey.grid(row=row, column=1)

        return box

    def run(self):
        headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit"
                   "/537.36 (KHTML, like Gecko) "
                   "Chrome/72.0.3626.121 Safari/537.36"}
        url = self.req_url.get()
        dataK = self.resKey.get()
        itemK = self.itemKey.get()
        res = get(url, headers=headers)
        data = res.json()
        listData = data[dataK]
        speed = self.get_speed()
        for i in range(len(listData)):
            if self.stop:
                break
            item = listData[i]
            if self.itemKey:
                item = item[itemK]
            self.keyResultContent(item)
            sleep(speed)
